use arboard::Clipboard;
use clap::Parser;
use std::env;
use std::fs::File;
use std::io::{self, Read, Write};
use std::path::{Path, PathBuf};

mod render;
mod utils;

#[derive(Parser, Debug)]
#[command(author, version, about, long_about = None)]
struct Args {
    #[arg(value_name = "FILE")]
    file: Option<PathBuf>,
    #[arg(short, long)]
    static_mode: bool,
    #[arg(short = 'C', long = "clipboard")]
    clipboard: bool,
}

fn run_static_mode(args: &Args) -> io::Result<()> {
    let (file_name, markdown_input) = if args.clipboard {
        let mut clipboard = Clipboard::new().unwrap();
        let content = clipboard.get_text().unwrap_or_else(|err| {
            eprintln!("Error reading from clipboard: {}", err);
            std::process::exit(1);
        });
        (String::from("Clipboard"), content)
    } else {
        match &args.file {
            Some(file_path) => {
                let mut file = File::open(&file_path).unwrap_or_else(|err| {
                    eprintln!("Error opening file {}: {}", file_path.display(), err);
                    std::process::exit(1);
                });
                let mut content = String::new();
                file.read_to_string(&mut content)?;
                (
                    file_path.file_name().unwrap().to_string_lossy().to_string(),
                    content,
                )
            }
            None => {
                let mut content = String::new();
                io::stdin().read_to_string(&mut content)?;
                (String::from("New file"), content)
            }
        }
    };

    let html_output = render::render_markdown_to_html(&markdown_input);
    let full_html = utils::build_full_html(&file_name, &html_output);

    //获取当前项目的路径
    let current_dir = env::current_dir().expect("Failed to get current directory");
    let temp_file_path = current_dir.join("markdown_preview.html");

    //创建文件并写入 HTML 内容
    let mut file = File::create(&temp_file_path)?;
    file.write_all(full_html.as_bytes())?;
    file.flush()?;

    let temp_path = temp_file_path.to_string_lossy().to_string();
    println!("Temporary HTML file created at: {}", temp_path);

    //打开浏览器
    utils::open_in_browser(&temp_path);

    println!("Press Enter to exit...");
    let mut input = String::new();
    io::stdin().read_line(&mut input)?;

    Ok(())
}

fn main() -> io::Result<()> {
    let args = Args::parse();

    if args.static_mode {
        run_static_mode(&args)?;
    } else {
        eprintln!("Error: --static-mode is required.");
        std::process::exit(1);
    }

    Ok(())
}
